<template>
  <div v-show="visible" :key="keyVisiable" class="reportPrint">
    <div v-show="hidePreview" class="print-loading">
      <a-spin tip="文件打印中..."></a-spin>
    </div>
    <div v-show="!hidePreview">
      <div class="print-btn">
        <a-button class="mr-2" @click="close">返回</a-button>
        <a-button v-if="!!fileUrl" type="primary" @click="toPrint">打印</a-button>
      </div>
      <div class="reportPrint-main">
        <div style="width: 80%; margin: auto; height: calc(100% - 90px); background: #fff">
          <iframe
            ref="refPrintIframe"
            scrolling="no"
            frameborder="0"
            :src="fileUrl"
            width="100%"
            height="100%"
          ></iframe>
        </div>
        <div v-if="loading" class="loading">
          <a-spin tip="文件加载中..."></a-spin>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { getFileBase64 } from '@@/api/common'
import { getPrintDocId } from '@@/api/report/reportPrint'
// import { useUserStore } from '@/store/modules/user'
// const userStore = useUserStore()

const props = defineProps<{
  getDocUrl?: any // 自定义获取文件id的接口
}>()
const refPrintIframe = ref()
const visible = ref(false)

const loading = ref(false)

const fileUrl = ref('')
const hidePreview = ref<boolean>(false)
const keyVisiable = ref()
function show(getDocParams, isPrint = false) {
  fileUrl.value = ''
  keyVisiable.value = new Date()
  const fn = props.getDocUrl || getPrintDocId
  fn(getDocParams)
    .then((docId) => {
      hidePreview.value = isPrint
      visible.value = true
      loading.value = true
      formatDoc(docId, isPrint)
    })
    .catch(() => {
      close()
    })
}
const formatDoc = (docId, isPrint) => {
  getFileBase64({ docId, orgId: '0' })
    .then((res) => {
      const blob = base64ImgtoFile(res)
      getPdfCount(blob)
      const blobUrl = window.URL.createObjectURL(blob)
      fileUrl.value = blobUrl + '#toolbar=0'
      // 如果是直接打印，等结束后，直接执行打印操作
      if (isPrint) {
        nextTick(() => {
          refPrintIframe.value.addEventListener('load', () => {
            toPrint()
          })
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
    .catch(() => {
      if (isPrint) {
        close()
      }
    })
}

function base64ImgtoFile(data) {
  const bstr = atob(data) //atob() 方法用于解码使用 base-64 编码的字符串
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `file.pdf`, {
    type: 'application/pdf'
  })
}

const pdfPages = ref(0)
function getPdfCount(fileData) {
  const reader: any = new FileReader()
  reader.readAsBinaryString(fileData)
  reader.onloadend = () => {
    pdfPages.value = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
  }
}

function close() {
  visible.value = false
  loading.value = false
  hidePreview.value = false
  refPrintIframe.value?.removeEventListener('load', () => {
    toPrint()
  })
}
const toPrint = () => {
  if (refPrintIframe.value) {
    refPrintIframe.value.contentWindow.print()
    if (hidePreview.value) {
      close()
    }
  }
}

defineExpose({
  show
})
</script>

<style lang="less">
.reportPrint {
  position: fixed;
  z-index: 99999999;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.6);

  .reportPrint-main,
  .loading,
  .print-loading {
    position: absolute;
    left: 0;
    right: 0;
    top: 60px;
    bottom: 40px;
  }
  .loading,
  .print-loading {
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 2;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.1);
  }
  .print-loading {
    background: rgba(100, 100, 100, 0.1);
    .ant-spin {
      color: #fff;
      .ant-spin-dot-item {
        background: #fff;
      }
    }
  }
  .print-btn {
    height: 50px;
    line-height: 50px;
    background: #fff;
    width: 80%;
    margin: 10px auto 0;
    text-align: right;
    padding: 0 10px;
  }
}
</style>
